package com.woniu.util;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.PullImageCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.core.DockerClientBuilder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 操作docker的工具类
 */
@Component
public class DockerClientUtils {
    /**
     * 连接Docker服务器
     * @return
     */
    public static DockerClient connectDocker(String dockerInstance){
        DockerClient dockerClient = DockerClientBuilder.getInstance(dockerInstance).build();
        dockerClient.infoCmd().exec();
        return dockerClient;
    }
    /**
     * repository 镜像名称:tag名称
     **/
    public PullImageCmd pullImage(DockerClient client, String repository){
        PullImageCmd pullImageCmd = client.pullImageCmd(repository);
        return pullImageCmd;
    }
    /**
     * 创建容器
     * @param client
     * @return
     */
    public CreateContainerResponse createContainers(DockerClient client, String containerName, String imageName){
        // 拉取镜像
        pullImage(client, imageName);
        // 映射端口8080 —> 8081
        // ExposedPort 容器的端口号
        ExposedPort tcp80 = ExposedPort.tcp(8080);
        Ports portBindings = new Ports();
        portBindings.bind(tcp80, Ports.Binding.bindPort(8081)); // 该8081端口是指宿主机的端口号
        CreateContainerResponse container = client.createContainerCmd(imageName)
                .withName(containerName)
                .withHostConfig(HostConfig.newHostConfig().withPortBindings(portBindings))
                .withExposedPorts(tcp80).exec();
        return container;
    }
    /**
     * 启动容器
     * @param client
     * @param containerId
     */
    public void startContainer(DockerClient client,String containerId){
        client.startContainerCmd(containerId).exec();
    }
    /**
     * 停止容器
     * @param client
     * @param containerId
     */
    public static void stopContainer(DockerClient client, String containerId){
        client.stopContainerCmd(containerId).exec();
    }
    /**
     * 删除容器
     * @param client
     * @param containerId
     */
    public static void removeContainer(DockerClient client, String containerId){
        client.removeContainerCmd(containerId).exec();
    }

//    判断容器是否存在

    public Container getContainerCmd(DockerClient client, String containerName) {
        List<Container> containers = client.listContainersCmd().withShowAll(true).exec();
        for (Container container:containers){
           if(container.getNames().toString().contains("/"+containerName)){
               return container;
           }
        }

        return null;
    }



}
